﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace MIAP.Negocio.Utiles
{
    public static class StringAndStream
    {
        /// <summary>
        /// regresa en un string el contenido del Stream
        /// </summary>
        /// <param name="pstream"></param>
        /// <returns></returns>
        public static string GenerateStringFromStream(Stream pstream)
        {
            var regreso = string.Empty;
            using (var reader = new StreamReader(pstream))
            {
                regreso = reader.ReadToEnd();
            }
            return regreso;
        }

        /// <summary>
        /// regresa en un stream el contenido del string
        /// </summary>
        /// <param name="stringOrigen"></param>
        /// <returns></returns>
        public static Stream GenerateStreamFromString(string stringOrigen)
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            writer.Write(stringOrigen);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }

        /// <summary>
        /// a partir de un stream regresa el contenido de este en un arreglo de bytes
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static byte[] ReadFully(Stream input)
        {
            var buffer = new byte[16 * 1024];
            using (var ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

        /// <summary>
        /// a partir de un arraglo de bytes regresa un stream
        /// </summary>
        /// <param name="byteArray"></param>
        /// <returns></returns>
        public static Stream GenerateStreamFromBytes(byte[] byteArray)
        {
            return  new MemoryStream(byteArray);
        }
    }
}
